package com.xxl.base_ui.util;

import com.google.gson.Gson;
import com.tencent.mmkv.MMKV;

import java.util.ArrayList;
import java.util.List;

public class MmkvUtil {

    private static MMKV mmkv;

    public static MMKV getInstance() {
       /* if (null == mmkv) {
            synchronized (MmkvUtil.class) {
                if (null == mmkv) {
                    mmkv = MMKV.defaultMMKV();
                }
            }
        }*/
        return MMKV.mmkvWithID("mmkvInit", MMKV.MULTI_PROCESS_MODE);
    }

    /**
     * 保存list数据
     *
     * @param list
     * @param name
     * @param <T>
     * @return`
     */
    public static <T> void setArray(List<T> list, String name) {
        MMKV kv = MMKV.defaultMMKV();
        clear(name, kv);
        kv.putInt(name + "size", list.size());
        for (int i = 0; i < list.size(); i++) {
            kv.encode(name + i, new Gson().toJson(list.get(i)));
        }
    }

    /**
     * 获取list
     *
     * @param name
     * @param bean
     * @param <T>
     * @return
     */
    public static <T> ArrayList<T> getArray(String name, T bean) {
        MMKV kv = MMKV.defaultMMKV();
        ArrayList<T> list = new ArrayList<T>();
        int size = kv.getInt(name + "size", 0);
        for (int i = 0; i < size; i++) {
            if (kv.getString(name + i, null) != null) {
                try {
                    list.add((T) new Gson().fromJson(kv.getString(name + i, null), bean.getClass()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
        return list;
    }

    private static void clear(String name, MMKV kv) {
        kv.putInt(name + "size", 0);
        int size = kv.getInt(name + "size", 0);
        for (int i = 0; i < size; i++) {
            if (kv.getString(name + i, null) != null) {
                kv.remove(name + i);
            }
        }
    }


}
